<template>
  <div class="courseware">
    <div
      v-for="(item, index) in listData.resList[programmeIndex].resList[
        classHourIndex
      ].resCoursewareList"
      :key="index"
      class="tags-box marginT30"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="block">
            <!-- item.files -->
            <el-image :src="item.files" />
          </div>
        </el-col>
        <el-col :span="6">
          <el-button type="text" @click="openOuter(item, index)">修改</el-button>
          <el-button type="text" @click="delOuterTags(item, index)">删除</el-button>
        </el-col>
      </el-row>
      <div v-for="(tagsItem, tagsInx) in item.tagList" :key="tagsInx">
        <div class="line-height30">文件标签</div>
        <div style="display: inline-block; border: 1px solid #ccc;">
          <div class="tags-item">
            <div class="left">{{ tagsItem.tagName }} ：</div>
            <div class="center">
              <el-tag
                v-for="(tag, inx) in tagsItem.tagsArr"
                :key="inx"
                style=" background-color: white; border-color: white;"
              >{{ tag.tagsName }}</el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="marginT40 upload">
      <div class="avatar-uploader" @click="openOuter('')">
        <div class="uploader-box">
          <div>
            <i class="el-icon-plus avatar-uploader-icon uploader-icon" />
          </div>
          <div class="el-upload__text upload__text marginT10" style="font-size:16px;">上传文件</div>
        </div>
      </div>
    </div>

    <!-- <div class="block marginT20">
      <div class="demonstration fs-14">文件标签</div>
      <el-cascader
        v-model="selectedOptions"
        class="marginT10"
        :options="options"
        :props="props"
        clearable
      />
    </div>-->

    <el-dialog :visible.sync="outerVisible" width="800px" :close-on-click-modal="false">
      <el-upload
        class="avatar-uploader"
        :action="action"
        :header="uploadHeader"
        :data="uploadForm"
        :show-file-list="false"
        :on-success="uploadSuccess"
        :before-upload="beforeUpload"
      >
        <div class="uploader-text-box uploader-box">
          <img v-if="outerDialogObj.files" :src="outerDialogObj.files" class="avatar" />
          <div v-else>
            <i class="el-icon-plus avatar-uploader-icon uploader-icon" />
            <div class="el-upload__text upload__text fs-16 marginT10">上传文件</div>
          </div>
        </div>
      </el-upload>
      <div class="line-height30 marginT20">文件标签</div>
      <div
        v-for="(tagsItem, tagsInx) in outerDialogObj.tagList"
        :key="tagsInx"
        class="tags-box marginT10"
      >
        <div style=" border: 1px solid #ccc;">
          <div class="tags-item">
            <div class="left">{{ tagsItem.tagName }} ：</div>
            <div class="center">
              <el-tag
                v-for="(tag, inx) in tagsItem.tagsArr"
                :key="inx"
                style=" background-color: white; border-color: white;"
              >{{ tag.tagsName }}</el-tag>
            </div>
            <div class="right">
              <el-button type="text" @click="open(tagsItem, tagsInx)">修改</el-button>
              <el-button type="text" @click="delTags(tagsItem, tagsInx)">删除</el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="button-box">
        <el-button type="primary" size="medium" round @click="open('')">添加标签</el-button>
      </div>

      <tagsDialog
        v-if="dialogVisible"
        :list="dialogObj"
        :append-to-body="true"
        :dialog-visible="dialogVisible"
        @Callback="dialogCallback"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="outerVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOuter">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tagsDialog from './tagsDialog';
import { preUpload } from '@/api/uploads';
import {
  personPrepareLessonUpdate,
  saveResCourseware,
  deleteResCourseware
} from '@/api/content';
import { updateTags } from './util';
import { tagsObjSwitch } from '@/utils/categoryOrTags';

export default {
  name: 'Courseware',
  components: {
    tagsDialog
  },
  props: ['list', 'option', 'programmeInx', 'classHourInx'],
  data () {
    return {
      programmeIndex: this.programmeInx,
      classHourIndex: this.classHourInx,
      options: this.option,
      listData: JSON.parse(JSON.stringify(this.list)),
      action: 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadHeader: {
        'Content-Type': 'multipart/form-data'
      },
      uploadForm: {},
      resCoursewareList: {
        files: null,
        fragments: null,
        id: null,
        metadataThemeId: null,
        tagList: []
      }, // 课堂实录

      outerVisible: false, // 外层dialog
      files: null, // 临时存储url
      dialogVisible: false,
      outerDialogObj: {
        files: null,
        id: null,
        metadataThemeId: null,
        tagList: null,
        isAdd: null
      },
      dialogObj: {
        GROWTH_CLASSIFY: null,
        STAGE: null,
        SUBJECT: null,
        DOWNSTATUS: null,
        keynote: null,
        abilityArr: null,
        tagList: null,
        isAdd: null
      }
    };
  },
  computed: {},
  watch: {
    programmeInx (newName, oldName) {
      this.programmeIndex = newName;
    },
    classHourInx (newName, oldName) {
      console.log('更新');
      this.classHourIndex = newName;
      this.updateResCoursewareList();
    }
  },
  created () {
    console.log(
      this.listData.resList[this.programmeIndex].resList[this.classHourIndex]
        .resCoursewareList
    );
    console.log(
      this.programmeIndex,
      this.classHourIndex,
      'courseware课件:',
      this.listData
    );
    this.dialogObj = {
      GROWTH_CLASSIFY: this.listData.GROWTH_CLASSIFY,
      STAGE: this.listData.STAGE,
      SUBJECT: this.listData.SUBJECT,
      DOWNSTATUS: true
    };

    this.updateResCoursewareList();
  },
  methods: {
    // 打开外部dialog
    openOuter (items, index) {
      console.log('外层:', items, index);
      this.outerVisible = true;
      this.outerInx = index !== null && index !== undefined ? index : '';

      if (items) {
        this.outerDialogObj.files = JSON.parse(JSON.stringify(items.files));
        this.outerDialogObj.id = JSON.parse(JSON.stringify(items.id));
        this.outerDialogObj.metadataThemeId = JSON.parse(
          JSON.stringify(items.metadataThemeId)
        );
        this.outerDialogObj.tagList = JSON.parse(JSON.stringify(items.tagList));
        this.outerDialogObj.isAdd = false;
      } else {
        this.outerDialogObj = {
          files: null,
          id: null,
          metadataThemeId: null,
          tagList: [],
          isAdd: true
        };
      }
    },
    delOuterTags (item, index) {
      console.log(
        this.listData.resList[this.programmeIndex].resList[this.classHourIndex]
          .resCoursewareList
      );
      const msg = '确认是否删除该课件！';
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var teachingDesignResId = this.listData.resList[this.programmeIndex]
            .resList[this.classHourIndex].id;
          deleteResCourseware(item.id, teachingDesignResId).then(res => {
            this.listData.resList[this.programmeIndex].resList[
              this.classHourIndex
            ].resCoursewareList.splice(index, 1);
          });
        })
        .catch(() => {
          // 取消操作
          console.log('cancel');
        });
    },
    saveOuter () {
      var _this = this;

      _this.saveTags().then(() => {
        var resCoursewareListBox =
          _this.listData.resList[_this.programmeIndex].resList[
          _this.classHourIndex
          ];

        var keyPointTagList = []; // 重难点
        var improvementTagList = []; // 能力提升点
        if (_this.checkArr(_this.outerDialogObj.tagList)) {
          _this.outerDialogObj.tagList.map(tagItem => {
            keyPointTagList.push({
              id: tagItem.tagId,
              name: tagItem.tagName
            });
            if (_this.checkArr(tagItem.tagsArr)) {
              tagItem.tagsArr.map(tagsItem => {
                improvementTagList.push({
                  id: tagsItem.tagsId,
                  name: tagsItem.tagsName
                });
              });
            }
          });
        }
        console.log('resCoursewareListBox:', resCoursewareListBox);
        console.log('outerDialogObj:', _this.outerDialogObj);
        console.log('keyPointTagList:', keyPointTagList);
        console.log('improvementTagList:', improvementTagList);
        console.log('this.outerInx:', this.outerInx);

        var data = {
          fileIds: _this.outerDialogObj.files || '',
          id: _this.outerDialogObj.id || '',
          keyPointTagList: keyPointTagList,
          improvementTagList: improvementTagList,
          teachingDesignId: _this.listData.baseInfo.id,
          teachingDesignResId: resCoursewareListBox.id
        };

        console.log('data:', data);

        saveResCourseware(data).then(res => {
          var obj = {
            files: _this.outerDialogObj.files,
            id: res.data.id,
            metadataThemeId: _this.outerDialogObj.metadataThemeId,
            tagList: _this.outerDialogObj.tagList
          };
          console.log('obj:', obj);
          this.outerInx !== ''
            ? resCoursewareListBox.resCoursewareList.splice(
              this.outerInx,
              1,
              obj
            )
            : resCoursewareListBox.resCoursewareList.push(obj);

          this.outerVisible = false;
          this.$message({
            message: '保存成功',
            type: 'success'
          });
        });
      });
    },
    delTags (item, index) {
      const msg = '确认是否删除该标签！';
      this.$confirm(msg, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.outerDialogObj.tagList.splice(index, 1);
        })
        .catch(() => {
          // 取消操作
          console.log('cancel');
        });
    },
    open (items, index) {
      console.log('options:', this.options);
      console.log(items, !items, index);
      this.tagsIndex = index || 0;

      console.log(this.outerDialogObj);

      this.dialogObj.keynote = items.tagId || '';
      this.dialogObj.keynoteValue = items.tagName || '';
      var key = [];
      if (JSON.stringify(items.tags) !== '{}') {
        for (var i in items.tags) {
          key.push(i);
        }
      }
      this.dialogObj.abilityArr = key;
      this.dialogObj.isAdd = !items;
      this.dialogObj.tagList = this.outerDialogObj.tagList;
      this.dialogVisible = true;
    },

    handleClose (tag, inx, index) {
      var obj = this.listData.resList[this.programmeIndex].resList[
        this.classHourIndex
      ].resCoursewareList[index].tagList;
      for (var i in obj) {
        if (this.checkArr(obj[i].tagsArr)) {
          for (var j in obj[i].tagsArr) {
            console.log(obj[i].tagsArr[j].tagsId);

            if (obj[i].tagsArr[j].tagsId === tag.tagsId) {
              obj[i].tagsArr.splice(j, 1);
            }
          }
        }
      }
    },
    // 更新课件
    updateResCoursewareList () {
      var obj = this.listData.resList[this.programmeIndex].resList[
        this.classHourIndex
      ].resCoursewareList;

      var arr = [];
      this.listData.resList[this.programmeIndex].resList[
        this.classHourIndex
      ].resCoursewareList = obj.concat(arr);

      var newArr = this.listData.resList[this.programmeIndex].resList[
        this.classHourIndex
      ].resCoursewareList;

      newArr.map((item, index) => {
        if (this.checkArr(item.tagList)) {
          item.tagList.map((items, indexs) => {
            if (JSON.stringify(items.tags) !== '{}') {
              items.tagsArr = tagsObjSwitch(items.tags);
            } else {
              items.tagsArr = [];
            }
          });
        }
      });
    },
    uploadSuccess (res, file) {
      this.outerDialogObj.files = this.files;
    },
    beforeUpload (file) {
      // const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/
      // if (!imgStr.test(file.name)) {
      //   this.$message.error('上传格式不对，请重新上传!')
      //   return false
      // }
      let continueUpload = false;
      return new Promise((resolve, reject) => {
        preUpload({
          biz: 'OPEN',
          name: file.name,
          size: file.size
        })
          .then(res => {
            this.action = res.data.action;
            this.uploadForm = res.data.parameters;
            continueUpload = true;
            this.files = res.data.uri;
            resolve(continueUpload);
          })
          .catch(err => {
            reject(continueUpload);
          });
      });
    },

    // 保存栏目标签-分类标签-简介
    saveTags () {
      var _this = this;
      return new Promise(function (resolve, reject) {
        _this.listData = updateTags(_this.listData, _this.options);
        var tagsData = {
          categoryTag: _this.listData.categoryTag,
          columnTag: _this.listData.columnTag,
          id: _this.listData.baseInfo.id,
          profiles: _this.listData.baseInfo.profiles
        };
        personPrepareLessonUpdate(tagsData).then(res => {
          resolve();
        });
      });
    },

    dialogCallback (obj) {
      console.log(
        'resCoursewareList',
        this.listData.resList[this.programmeIndex].resList[this.classHourIndex]
          .resCoursewareList
      );

      console.log('dialogCallback:', obj);
      console.log(' this.outerDialogObj:', this.outerDialogObj);

      this.dialogVisible = obj.dialogVisible;
      // var _this = this;
      var abilityObj = {};
      if (this.checkArr(obj.ability)) {
        for (var i in obj.ability) {
          abilityObj[obj.ability[i].tagsId] = obj.ability[i].tagsName;
        }
      }

      // if (this.checkArr(obj.keynote)) {
      //   var tagsObj = {
      //     tagId: obj.keynote[0].tagsId,
      //     tagName: obj.keynote[0].tagsName,
      //     tags: abilityObj,
      //     tagsArr: obj.ability
      //   };

      var tagsObj = {
        tagId: obj.keynote[0].tagsId,
        tagName: obj.keynote[0].tagsName,
        tags: abilityObj,
        tagsArr: obj.ability
      };

      if (obj.isAdd) {
        this.outerDialogObj.tagList.push(tagsObj);
      } else {
        this.outerDialogObj.tagList.splice(this.outerInx, 1, tagsObj);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.button-box {
  margin-top: 24px;

  .default {
    width: 94px;
    height: 40px;
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    margin-right: 30px;
    cursor: pointer;
  }
  .submit {
    width: 128px;
    height: 40px;
    border: none;
    background: rgba(84, 184, 123, 1);
    border-radius: 4px;

    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
    line-height: 24px;
    cursor: pointer;
  }
}
.tags-box {
  .tags-item {
    display: flex;
    padding-left: 15px;
    align-items: center;

    .left {
      width: 110px;
    }
    .center {
      flex: 1;
    }
    .right {
      width: 110px;
      box-sizing: content-box;
      padding-left: 30px;
    }
  }
}
.avatar {
  width: 100%;
}
.uploader-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  flex-direction: column;
  cursor: pointer;
}
</style>
